package cn.xiyun.xiyuncc.service.impl;

import cn.xiyun.xiyuncc.domain.AlipayInfo;
import cn.xiyun.xiyuncc.domain.PayOrder;
import cn.xiyun.xiyuncc.dto.AliPayDto;
import cn.xiyun.xiyuncc.exception.OperationException;
import cn.xiyun.xiyuncc.service.IAlipayInfoService;
import cn.xiyun.xiyuncc.service.IPayOrderService;
import cn.xiyun.xiyuncc.service.IPayService;
import cn.xiyun.xiyuncc.util.AssertUtil;
import cn.xiyun.xiyuncc.utils.AliPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class PayServiceImpl implements IPayService {

    @Autowired
    private IPayOrderService payOrderService;

    @Autowired
    private IAlipayInfoService alipayInfoService;

    /**
     * 支付
     * @param payDto
     * @return
     */
    @Override
    public String AllPay(AliPayDto payDto) {
        AssertUtil.isNotNull(payDto,"订单数据错误请重新下单");
        //根据订单号查询订单参数
        PayOrder payOrder = payOrderService.selectOrderNo(payDto.getOrderNo());
        AssertUtil.isNotNull(payOrder,"订单信息未生成请稍后重试");
        AssertUtil.isEquals(payOrder.getPayStatus().toString(),PayOrder.PAY_WAITING.toString(),"订单已支付请勿重复支付");
        if (payOrder.getPayStatus().equals(PayOrder.PAY_CANCEL)) throw new OperationException("订单已超时请重新下单");

        // 查询支付配置 选择支付方式
        String AlipayPage = ChoicePayMethod(payDto, payOrder);
        return AlipayPage;
    }

    /**
     * 根据PayType选择支付方式
     * @return String
     */
    private String ChoicePayMethod(AliPayDto payDto,PayOrder payOrder){
        switch (payDto.getPayType()){
            case 1:
                // 查询支付配置
                AlipayInfo alipayInfo = alipayInfoService.selectById(1L);
                // 调用支付宝支付工具类
                String AlipayPage = AliPayUtil.payAlipay(alipayInfo, payOrder);

                return AlipayPage;
            case 2:
                // TODO 其他支付方式调用
                return null;
        }
        return null;
    }

    /**
     * 支付宝退款
     * @param orderNo
     * @return
     * @throws Exception
     */
    public String ChoiceRefundMethod(String orderNo) {
        PayOrder payOrder = payOrderService.selectOrderNo(orderNo);
        AssertUtil.isNotNull(payOrder,"未查询到订单信息");
                // 查询支付配置
                AlipayInfo alipayInfo = alipayInfoService.selectById(1L);
                // 调用支付宝支付工具类 退款
                String AlipayPage = AliPayUtil.refundAlipay(alipayInfo, payOrder);

        System.out.println(AlipayPage);
        // TODO 发送事务消息更改订单状态更改支付单状态
        //  将课程与用户表数据删除


                return AlipayPage;


    }
}
